<script setup lang="ts">
import * as echarts from 'echarts';
import { ref , markRaw , onMounted, reactive , onBeforeUnmount , onActivated , watch , nextTick} from 'vue';
interface DataType {
    name: string;
    value: number;
}
const props = withDefaults( defineProps<{
    width?: string,
    height?: string,
    theme?: string,
    bgColor?: string,
    title: string,
    subtitle: string,
    data: DataType[],
}>(),{
    width: '100%',
    height: '380px',
    data: () => [],
});

const chartRef = ref();

const state = reactive({
    chart: null as any,
    nvll: ['',null,undefined],
})

onMounted(() => {
    //initChart();
    window.addEventListener('resize',echartsResizeFun);
});

onActivated(() => {
    echartsResizeFun();
});

watch(() => [props.data , props.theme ], () => {
    nextTick(() => {
        initChart();
    });
}, {deep: true , immediate: true});

function initChart() {
    if(state.nvll.indexOf(state.chart) === -1) state.chart.dispose();
    state.chart = markRaw(echarts.init(chartRef.value,props.theme));
    const option = {
        backgroundColor: props.bgColor,
        title: {
            text: props.title,
            subtext: props.subtitle,
            left: 'left'
        },
        tooltip: {
            trigger: 'item'
        },
        // legend: {
        //     orient: 'vertical',
        //     left: 'right'
        // },
        series: [
            {
            name: '单位：元',
            type: 'pie',
            radius: '60%',
            data: props.data,
            emphasis: {
                itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
            }
        ]
    };
    state.chart.setOption(option);
}

function echartsResizeFun() {
    state.chart && state.chart.resize();
}

onBeforeUnmount(() => {
    window.removeEventListener('resize',echartsResizeFun);
    if(state.chart) {
        state.chart.dispose();
        state.chart = null;
    }
})
</script>

<template>
    <el-card shadow="hover">
        <div ref="chartRef" :style="{width: props.width, height: props.height}">

        </div>
    </el-card>
</template>

<style scoped>

</style>